import asyncio
from aiolimiter import AsyncLimiter
import pandas as pd
import logging
from datetime import datetime

# QPS限制器，每秒最多15个请求
limiter = AsyncLimiter(15, 1)

# 配置日志，输出到文件
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[logging.FileHandler("parallel_api_test.log", encoding="utf-8")],
)


async def fake_fetch(data, id_):
    async with limiter:
        send_time = datetime.now()  # 记录真正获得令牌的时间
        await asyncio.sleep(5)
        result = f"模拟返回_{id_}"
        return_time = datetime.now()
        log_msg = (
            f"ID:{id_} | 发送时间:{send_time} | 返回时间:{return_time} | "
            f"输入内容:{data} | 返回内容:{result}"
        )
        logging.info(log_msg)
        return id_, data, result, send_time, return_time


async def main(texts):
    results = []
    tasks = [fake_fetch(text, id_) for id_, text in texts]
    for coro in asyncio.as_completed(tasks):
        id_, text, result, send_time, return_time = await coro
        print(f"ID:{id_} 结果:{result}")
        results.append((id_, text, result, send_time, return_time))
    return results


def save_results_to_excel(results, filename="results_test.xlsx"):
    df = pd.DataFrame(
        results, columns=["ID", "输入内容", "返回内容", "发送时间", "返回时间"]
    )
    df.to_excel(filename, index=False)


def read_texts_from_excel(file_path):
    df = pd.read_excel(file_path)
    return list(zip(df.iloc[:, 0], df.iloc[:, 1]))


if __name__ == "__main__":
    input_excel = r"C:\Users\JP\Desktop\测试文本1.xlsx"  # 你的输入Excel文件名
    texts = read_texts_from_excel(input_excel)
    results = asyncio.run(main(texts))
    save_results_to_excel(results)
